package org.gap.wizards.effects;

import java.awt.Point;

import org.gap.wizards.views.ViewPlatform;
import org.gap.wizards.views.ViewPlatform.Color;

public class Ray implements VisualEffect {
	private Point source;
	private Point destination;
	private final Color color;
	private final int milliSeconds;

	public Ray(Color color, int milliSeconds) {
		this.color = color;
		this.milliSeconds = milliSeconds;
	}
	
	@Override
	public int getX() {
		return source.x;
	}
	
	@Override
	public int getY() {
		return source.y;
	}

	@Override
	public void setSource(Point source) {
		this.source = source;
	}
	
	@Override
	public void setDestination(Point destination) {
		this.destination = destination;
	}

	@Override
	public void draw(ViewPlatform console) {
		console.saveBuffer();
		printText(console, "*");
		console.restore();
	}

	private void holdEffectForGivenTime() {
		try {
			Thread.sleep(milliSeconds);
		} catch (InterruptedException e) {
		}
	}

	private void printText(ViewPlatform console, String raySymbol) {
		Point path = new Point(source);
		while(!path.equals(destination)) {
			console.saveBuffer();
			path.x = move(path.x, destination.x);
			path.y = move(path.y, destination.y);
			console.print(path.x, path.y, color, raySymbol);
			console.refresh();
			holdEffectForGivenTime();
			console.restore();
		}
		console.restore();
		console.refresh();
	}

	private int move(int start, int destination) {
		if (start == destination) {
			return start;
		}
		return start > destination? start - 1: start + 1;
	}
}
